package com.tebiecloud.order.server.controller.feign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.DateUtils;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.order.client.model.entity.OrderEvaluate;
import com.tebiecloud.order.client.model.entity.OrderGoods;
import com.tebiecloud.order.client.model.entity.Orderr;
import com.tebiecloud.order.client.model.vo.IncomeList;
import com.tebiecloud.order.client.model.vo.NotArrivedList;
import com.tebiecloud.order.client.model.vo.OrderRetailList;
import com.tebiecloud.order.client.service.IOrderServiceClient;
import com.tebiecloud.order.server.service.OrderEvaluateService;
import com.tebiecloud.order.server.service.OrderGoodsService;
import com.tebiecloud.order.server.service.OrderrService;
import com.tebiecloud.order.server.service.feign.RetailOrderServiceClient;
import com.tebiecloud.order.server.service.feign.StoreServiceClient;
import com.tebiecloud.retail.client.model.entity.RetailOrder;
import com.tebiecloud.store.client.model.entity.Store;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/feign/order")
public class OrderOrderController implements IOrderServiceClient {

    @Autowired
    RetailOrderServiceClient retailOrderServiceClient;

    @Autowired
    OrderrService orderService;

    @Autowired
    OrderGoodsService orderGoodsService;

    @Autowired
    StoreServiceClient storeServiceClient;

    @Autowired
    OrderEvaluateService orderEvaluateService;

    /**
     * 获取未到账余额
     * 如果有已退款的，需要在一周内显示，一周后不显示
     *
     * @param userId
     * @return
     */
    @PostMapping("notArrivedList")
    @Override
    public ResultBody<List<NotArrivedList>> selectNotArrivedList(@RequestParam("userId") Long userId) {
        List<NotArrivedList> notArrivedLists = new ArrayList<>();
        //获取买跟卖的订单列表
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("page", 1);
        map.put("limit", 9999);
        map.put("status", "2,6");
        ResultBody<Page<RetailOrder>> resultBody = retailOrderServiceClient.listMyRetailOrder(map);
        if (resultBody != null && resultBody.getCode() == ResultEnum.OK.getCode()) {
            List<RetailOrder> retailOrders = resultBody.getData().getRecords();
            List<Long> orderIds = new ArrayList<>();
            for (RetailOrder retailOrder : retailOrders) {
                orderIds.add(retailOrder.getOrderId());
            }
            if(orderIds.size()>0){
                //根据订单id列表查询订单信息
                notArrivedLists = orderService.selectNotArrivedList(userId, orderIds);
            }
        }
        return ResultBodyUtils.ok(notArrivedLists);
    }

    /**
     * 获取收益列表
     * 传month查询月的收益
     * 传day查询天的收益
     *
     * @param month YYYY-MM
     * @param day   YYYY-MM-dd
     * @return
     */
    @PostMapping("incomeList")
    @Override
    public ResultBody<IncomeList> selectIncomeList(
            @RequestParam(value = "userId") Long userId,
            @RequestParam(value = "month", required = false) String month,
            @RequestParam(value = "day", required = false) String day) {
        IncomeList incomeList = new IncomeList();
        //获取买跟卖的订单列表
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("page", 1);
        map.put("limit", 9999);
        map.put("status", 4);
        if (StringUtils.isNotEmpty(month)) {
            map.put("startTime", DateUtils.getFirstDayOfMonth(month));
            map.put("endTime", DateUtils.getLastDayOfMonth(month));
        }
        if (StringUtils.isNotEmpty(day)) {
            map.put("startTime", DateUtils.getFirstTimeOfDay(day));
            map.put("endTime", DateUtils.getLastTimeOfDay(day));
        }
        ResultBody<Page<RetailOrder>> resultBody = retailOrderServiceClient.listMyRetailOrder(map);
        if (resultBody != null && resultBody.getCode() == ResultEnum.OK.getCode()) {
            //取订单id列表
            List<RetailOrder> retailOrders = resultBody.getData().getRecords();
            List<Long> orderIdList = new ArrayList<>();
            for (RetailOrder retailOrder : retailOrders) {
                orderIdList.add(retailOrder.getOrderId());
            }
            //判断是月收益
            if (StringUtils.isNotEmpty(month)) {
                //查询订单
                incomeList = orderService.selectIncomeList(orderIdList, month, null);
            }
            if (StringUtils.isNotEmpty(day)) {
                //查询订单
                incomeList = orderService.selectIncomeList(orderIdList, null, day);
            }
        }
        return ResultBodyUtils.ok(incomeList);
    }

    /**
     * 获取订单信息
     * @param orderId
     * @return
     */
    @PostMapping("selectOrder")
    @Override
    public ResultBody<Orderr> selectOrder(@RequestParam("orderId") long orderId) {
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("order_id", orderId);
        Orderr orderr = orderService.getOne(orderrQueryWrapper, false);
        if (orderr != null) {
            return ResultBodyUtils.ok(orderr);
        }

        return ResultBodyUtils.failed(null);
    }

    /**
     * 获取订单信息
     *
     * @param orderId
     * @return
     */
    @PostMapping("selectOrderVo")
    @Override
    public ResultBody<OrderRetailList> selectOrderVo(long orderId) {
        OrderRetailList orderRetailList = new OrderRetailList();
        //查询订单
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("order_id", orderId);
        Orderr orderr = orderService.getOne(orderrQueryWrapper);
        if (orderr != null) {
            BeanUtils.copyProperties(orderr, orderRetailList);
            List<OrderGoods> orderGoodsList = orderGoodsService.listByOrderId(orderr.getOrderId(),null);
            if(orderGoodsList.size()>0){
                //获取门店信息
                ResultBody<Store> storeResultBody = storeServiceClient.getStore(orderGoodsList.get(0).getStoreId());
                if(storeResultBody!=null && storeResultBody.getCode() == ResultEnum.OK.getCode()){
                    Store store = storeResultBody.getData();
                    if(store!=null)orderRetailList.setStoreName(store.getName());
                }
            }
        }
        return ResultBodyUtils.ok(orderRetailList);
    }

    /**
     * 查询订单列表
     * @param storeId
     * @return
     */
    @PostMapping("selectOrderList")
    @Override
    public ResultBody<List<Orderr>> selectOrderList(@RequestParam("storeId") long storeId) {
        List<Orderr> orderrList = new ArrayList<>();
        //查询未核销完的
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("store_id",storeId);
        orderGoodsQueryWrapper.eq("sold",1);
        orderGoodsQueryWrapper.gt("remain_write_off_times",0);
        List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
        List<Long> orderIds = new ArrayList<>();
        if(orderGoodsList.size()>0){
            for(OrderGoods orderGoods:orderGoodsList){
                orderIds.add(orderGoods.getOrderId());
            }
            QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
            orderrQueryWrapper.in("order_id",orderIds);
            orderrQueryWrapper.eq("status",2);
            orderrList = orderService.list(orderrQueryWrapper);
        }
        return ResultBodyUtils.ok(orderrList);
    }

    /**
     * 获取没有支付，超时的订单
     * @return
     */
    @PostMapping("selectNotPayOrderList")
    @Override
    public ResultBody<List<Orderr>> selectNotPayOrderList(@RequestParam("status") int status,@RequestParam("ct") String ct) {
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("status",status);
        orderrQueryWrapper.lt("ct",ct);
        List<Orderr> orderrList = orderService.list(orderrQueryWrapper);
        return ResultBodyUtils.ok(orderrList);
    }

    /**
     * 更新订单信息
     * @param orderId 订单id
     * @param status 订单状态
     * @return
     */
    @PostMapping("updateOrder")
    @Override
    public ResultBody updateOrder(@RequestParam("orderId") long orderId,@RequestParam("status") int status) {
        //查询订单
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("order_id",orderId);
        Orderr orderr = orderService.getOne(orderrQueryWrapper);
        if(orderr!=null){
            if(status == 0 && orderr.getStatus() <= 1){
                UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
                orderrUpdateWrapper.eq("order_id",orderId);
                Orderr orderr1 = new Orderr();
                orderr1.setStatus(status);
                orderr1.setShutTime(new Date());//关闭订单时间
                orderService.update(orderr1,orderrUpdateWrapper);
            }
        }
        return ResultBodyUtils.ok();
    }

    @PostMapping("selectOrderEvaluate")
    @Override
    public ResultBody<OrderEvaluate>  selectOrderEvaluate(long orderId) {
        QueryWrapper<OrderEvaluate> orderEvaluateQueryWrapper = new QueryWrapper<>();
        orderEvaluateQueryWrapper.eq("order_id",orderId);
        orderEvaluateQueryWrapper.orderByDesc("ct");
        orderEvaluateQueryWrapper.last("LIMIT 1");
        OrderEvaluate orderEvaluate = orderEvaluateService.getOne(orderEvaluateQueryWrapper);
        return ResultBodyUtils.ok(orderEvaluate);
    }
}
